#include <stdio.h>
#include <pthread.h>
#include <signal.h>
#include <unistd.h>

pthread_mutex_t mutex = PTHREAD_MUTEX_INITIALIZER;
pthread_cond_t cond = PTHREAD_COND_INITIALIZER;
int current_thread = 0;

void *print_letter(void *arg) {
    char letter = *((char *)arg);
    while(1) {
        pthread_mutex_lock(&mutex);
        while(current_thread != (letter - 'a')) {
            pthread_cond_wait(&cond, &mutex);
        }
        printf("%c", letter);
        fflush(stdout);
        current_thread = (current_thread + 1) % 5;
        pthread_cond_broadcast(&cond);
        pthread_mutex_unlock(&mutex);
    }
    return NULL;
}
void timer_handler(int signum) {
   // pthread_exit(NULL);
	printf("finish...\n");
	return;
}
int main() {
    pthread_t threads[5];
    char letters[] = {'a', 'b', 'c', 'd', 'e'};
    for(int i = 0; i < 5; i++) {
        pthread_create(&threads[i], NULL, print_letter, (void *)&letters[i]);
    }
//    signal(SIGALRM, timer_handler);
    alarm(1);
    for(int i = 0; i < 5; i++) {
        pthread_join(threads[i], NULL);
    }
    printf("\n");
    return 0;
}

